package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.exception.BaseException;
import com.chen.mapper.PolicyMapper;
import com.chen.mapper.VmPolicyMapper;
import com.chen.pojo.common.PageResult;
import com.chen.pojo.dto.PolicyDto;
import com.chen.pojo.entry.Policy;
import com.chen.pojo.entry.VmPolicy;
import com.chen.pojo.vo.PolicyDetailsVo;
import com.chen.service.PolicyService;
import com.chen.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/8/22
 */
@Service
public class PolicyServiceImpl implements PolicyService {
    @Autowired
    private PolicyMapper policyMapper;
    @Autowired
    private VmPolicyMapper vmPolicyMapper;

    @Override
    public PageResult<Policy> searchList(Integer pageIndex, Integer pageSize, String policyName) {
        Page<Policy> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<Policy> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(policyName), Policy::getPolicyName, policyName);
        page = policyMapper.selectPage(page, wrapper);
        return PageUtils.mapperResult(page);
    }

    @Override
    public PageResult<PolicyDetailsVo> getVmInfoByPolicyId(Integer pageIndex, Integer pageSize, Integer policyId) {
        Page<PolicyDetailsVo> page = new Page<>(pageIndex, pageSize);
        page = policyMapper.selectVmInfoByPolicyId(page, policyId);
        return PageUtils.mapperResult(page);
    }

    @Override
    public Boolean updatePolicyById(Integer policyId, PolicyDto policyDto) {
        Policy policy = new Policy();
        policy.setPolicyId(policyId.toString());
        BeanUtils.copyProperties(policyDto, policy);
        policyMapper.updateById(policy);
        return true;
    }

    @Override
    public Boolean deleteById(Integer policyId) {
        LambdaQueryWrapper<VmPolicy> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VmPolicy::getPolicyId, policyId);
        VmPolicy vmPolicy = vmPolicyMapper.selectOne(wrapper);
        if (Objects.nonNull(vmPolicy)) {
            throw new BaseException("该策略正在使用，不能删除");
        }
        policyMapper.deleteById(policyId);
        return true;
    }

    @Override
    public Boolean add(PolicyDto policyDto) {
        Policy policy = new Policy();
        BeanUtils.copyProperties(policyDto, policy);
        policyMapper.insert(policy);
        return true;
    }
}
